package com.example.teaching_server.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 资源查询请求DTO
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "资源查询请求参数")
public class ResourceRequestDTO {

    @Positive(message = "子分类ID必须是正整数")
    @Schema(description = "三级菜单ID（子分类ID）", example = "5")
    private Long subcategoryId;

    @Positive(message = "资源类型ID必须是正整数")
    @Schema(description = "资源类型ID", example = "1", allowableValues = {"1", "2", "3", "4", "5"})
    private Integer typeId;

    @Schema(description = "搜索关键词", example = "数学课件")
    private String keyword;

    @Schema(description = "页码（从1开始）", example = "1")
    @Builder.Default
    private Integer page = 1;

    @Schema(description = "每页大小", example = "20")
    @Builder.Default
    private Integer size = 20;

    @Schema(description = "排序字段", example = "createdAt", allowableValues = {"name", "createdAt", "size"})
    private String sortBy;

    @Schema(description = "排序方向", example = "desc", allowableValues = {"asc", "desc"})
    private String sortDirection;

    /**
     * 获取查询偏移量
     */
    @Schema(description = "查询偏移量", accessMode = Schema.AccessMode.READ_ONLY)
    public Integer getOffset() {
        return (page - 1) * size;
    }

    /**
     * 验证查询条件是否有效
     */
    @Schema(description = "查询条件是否有效", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isValidQuery() {
        return subcategoryId != null || typeId != null ||
                (keyword != null && !keyword.trim().isEmpty());
    }

    /**
     * 获取排序字段（安全版本）
     */
    @Schema(description = "安全排序字段", accessMode = Schema.AccessMode.READ_ONLY)
    public String getSafeSortBy() {
        if (sortBy == null) return "createdAt";

        return switch (sortBy) {
            case "name", "createdAt", "size", "type" -> sortBy;
            default -> "createdAt";
        };
    }

    /**
     * 获取排序方向（安全版本）
     */
    @Schema(description = "安全排序方向", accessMode = Schema.AccessMode.READ_ONLY)
    public String getSafeSortDirection() {
        if (sortDirection == null) return "desc";
        return "asc".equalsIgnoreCase(sortDirection) ? "asc" : "desc";
    }

    /**
     * 构建默认查询请求
     */
    public static ResourceRequestDTO defaultQuery() {
        return ResourceRequestDTO.builder()
                .page(1)
                .size(20)
                .sortBy("createdAt")
                .sortDirection("desc")
                .build();
    }

    /**
     * 构建关键词搜索请求
     */
    public static ResourceRequestDTO keywordSearch(String keyword) {
        return ResourceRequestDTO.builder()
                .keyword(keyword)
                .page(1)
                .size(20)
                .sortBy("createdAt")
                .sortDirection("desc")
                .build();
    }
}
